
package isv
import (
	"github.com/astaxie/beego/orm"
	"dhfshop/models"
	"wxsdk/oauth"
)

type WeChatToken struct {
	OpenId       string `orm:"column(open_id);size(128);pk" json:"open_id"`
	AccessToken  string `orm:"column(access_token)" json:"access_token"`
	ExpiresIn    int64  `orm:"column(expires_in)" json:"expires_in"`
	RefreshToken string `orm:"column(refresh_token)" json:"refresh_token"`
	Scope        string `orm:"column(scope)" json:"scope"`
}

func init() {
    orm.RegisterModel(new(WeChatToken))   
}

// 创建或者更新微信token
func SaveWeChatToken(token *oauth.PubCode2SessionRsp) (err error) {
	o := models.GetDefaultDB()
	v := &WeChatToken{OpenId:token.Openid}
	m := &WeChatToken{OpenId:token.Openid,AccessToken:token.AccessToken,ExpiresIn:token.ExpiresIn,RefreshToken:token.RefreshToken,Scope:token.Scope}
	if err = o.Read(v); err == nil {
		if _, err = o.Update(m, "AccessToken", "ExpiresIn", "RefreshToken", "Scope"); err != nil {
			return err
		}
	}else{
	    if _, err = o.Insert(m); err != nil {
		    return err
		}
	}
	return nil
}


